<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="theme-color" content="#3367D6"/>
  <link rel="apple-touch-icon" href="/icons-192.png">
  <link rel="manifest" href="/manifest.json">

  

  

  
    <meta name="author" content="体奈">
  

  

  

  <title>python中with上下文管理 | 枕上书的技术博客</title>

  

  
    <link rel="icon" href="/favicon.ico">
  

  
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@1.1.3/index.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlightjs@9.16.2/styles/monokai.css">
  

  
<link rel="stylesheet" href="/hexo/css/style.css">

<meta name="generator" content="Hexo 5.4.0"></head>
<body>
  <div class="root-container">
    <!-- navbar -->
<nav class="navbar">
  <div class="navbar-content">
    <!-- logo -->
    <div class="navbar-logo">
      <a href="/hexo/">
        
          <img src="https://img0.baidu.com/it/u=285996501,2785962054&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg" alt="枕上书的技术博客" />
        
      </a>
    </div>
    <!-- link -->
    <div class="navbar-link">
      <div class="navbar-btn">
        <div></div>
        <div></div>
        <div></div>
      </div>
      <ul class="navbar-list">
        
          <li class="navbar-list-item"><a href="/hexo/">HOME</a></li>
        
      </ul>
    </div>
  </div>
</nav>

    
<!-- header container -->
<header class="header-container post">

  
  

  
  

  
  

  
  

  
  
    <div class="header-content">
      
        <div class="post-image" style="background-image: url(https://pic.netbian.com/uploads/allimg/201104/234353-1604504633d5cd.jpg)"></div>
      

      <div class="post-text">
        <div class="type-wrap">
          
        </div>
        <h1 class="title-wrap">python中with上下文管理</h1>
        <h2 class="title-sub-wrap">
          <strong>体奈</strong>
          <span>发布于</span>
          
  <a href="javascript:;" class="article-date">
    <time datetime="2018-07-13T07:21:41.000Z" itemprop="datePublished">2018-07-13</time>
  </a>

        </h2>
      </div>
    </div>
  

  
  
  
</header>

    <!-- 文章 -->

<!-- 文章内容 -->

<div class="body-container">
  <article class="content-container article-container">
    <div class="article-content">
      
      

      <section class="article-entry">
        <h2 id="上下文管理"><a href="#上下文管理" class="headerlink" title="上下文管理"></a>上下文管理</h2><h4 id="with语句是什么"><a href="#with语句是什么" class="headerlink" title="with语句是什么"></a>with语句是什么</h4><ul>
<li>with是一种上下文管理协议，目的在于从流程图中把 try,except 和finally 关键字和资源分配释放相关代码统统去掉，简化try….except….finlally的处理流程</li>
<li>所以使用with处理的对象必须有enter()和exit()这两个方法<ul>
<li>with通过enter方法初始化（enter方法在语句体执行之前进入运行）</li>
<li>然后在exit中做善后以及处理异常（exit()方法在语句体执行完毕退出后运行）</li>
</ul>
</li>
</ul>
<h4 id="with语句使用场景"><a href="#with语句使用场景" class="headerlink" title="with语句使用场景"></a>with语句使用场景</h4><ul>
<li>with 语句适用于对资源进行访问的场合，确保不管使用过程中是否发生异常都会执行必要的“清理”操作，释放资源</li>
<li>比如文件使用后自动关闭、线程中锁的自动获取和释放等</li>
</ul>
<h4 id="with处理文件操作的实例"><a href="#with处理文件操作的实例" class="headerlink" title="with处理文件操作的实例"></a>with处理文件操作的实例</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">PYTHON</span><br><span class="line">with open(&#39;&#x2F;etc&#x2F;passwd&#39;) as f:</span><br><span class="line">  for line in f:</span><br><span class="line">    print(line)</span><br><span class="line"></span><br><span class="line"># 这段代码的作用：打开一个文件，如果一切正常，把文件对象赋值给f，然后用迭代器遍历文件中每一行，当完成时，关闭文件；</span><br><span class="line"># 而无论在这段代码的任何地方，如果发生异常，此时文件仍会被关闭。</span><br><span class="line">PYTHON</span><br><span class="line">with open(&#39;a2.py&#39;,encoding&#x3D;&#39;utf8&#39;) as f:</span><br><span class="line">    print( f.readlines())</span><br><span class="line"></span><br><span class="line">try:</span><br><span class="line">    f &#x3D; open(&#39;a.py&#39;,encoding&#x3D;&#39;utf8&#39;)</span><br><span class="line">    f.read()</span><br><span class="line">except Exception as e:</span><br><span class="line">    print(print(e))</span><br><span class="line">finally:</span><br><span class="line">    f.close()</span><br></pre></td></tr></table></figure>
      </section>

      <section class="article-footer">
        
      </section>

      <section class="article-navs">
        
<nav class="card-container card-article-nav">
  <div class="card-list">
    
      <div id="article-nav-newer" class="card-item">
        <article>
          
          <a class="card-link article-nav-link" href="/hexo/2018/09/13/MongoDB%E7%9A%84%E5%9F%BA%E7%A1%80%E5%91%BD%E4%BB%A4/"></a>
          <strong class="article-nav-caption">Newer</strong>
          <p class="article-nav-title">
            
              MongoDB的基础命令
            
          </p>
        </article>
      </div>
    
    
      <div id="article-nav-older" class="card-item">
        <article>
          
          <a class="card-link article-nav-link" href="/hexo/2018/04/13/gitee%E7%9A%84%E5%9F%BA%E7%A1%80%E5%91%BD%E4%BB%A4/"></a>
          <strong class="article-nav-caption">Older</strong>
          <p class="article-nav-title">
            
              gitee的基础命令
            
          </p>
        </article>
      </div>
    
  </div>
</nav>

      </section>
    </div>
  </article>
</div>

    <!-- footer container -->
<footer id="footer" class="footer">
  <div class="footer-container">
    
    <div class="social-icons social-icons-footer">
      <a href="mailto:2314999784@qq.com" target="_blank" rel="noopener noreferrer">
  <svg class="icon icon-email" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <path d="M490.338462 592.738462c11.815385 11.815385 29.538462 11.815385 41.353846 0l445.046154-413.538462c7.876923-15.753846 5.907692-41.353846-25.6-41.353846l-880.246154 1.969231c-23.630769 0-43.323077 21.661538-25.6 41.353846l445.046154 411.569231zM984.615385 340.676923c0-19.692308-23.630769-31.507692-39.384616-17.723077L596.676923 643.938462c-23.630769 21.661538-53.169231 33.476923-84.676923 33.476923s-61.046154-11.815385-84.676923-31.507693L80.738462 322.953846c-15.753846-13.784615-39.384615-3.938462-39.384616 17.723077C39.384615 334.769231 39.384615 787.692308 39.384615 787.692308c0 43.323077 35.446154 78.769231 78.769231 78.76923h787.692308c43.323077 0 78.769231-35.446154 78.769231-78.76923V340.676923z"></path>
  </svg>
</a><a href="https://gitee.com/l17338172351" target="_blank" rel="noopener noreferrer">
  <svg class="icon icon-github" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <path d="M64.6 512c0 195.6 125.4 361.9 300.1 422.9 23.5 5.9 19.9-10.8 19.9-22.2v-77.6c-135.8 15.9-141.3-74-150.5-89-18.5-31.5-61.9-39.5-49-54.5 31-15.9 62.5 4 98.9 58 26.4 39.1 77.9 32.5 104.1 26 5.7-23.5 17.9-44.5 34.7-60.9-140.7-25.2-199.4-111.1-199.4-213.3 0-49.5 16.4-95.1 48.4-131.8-20.4-60.6 1.9-112.4 4.9-120.1 58.2-5.2 118.5 41.6 123.3 45.3 33.1-8.9 70.8-13.7 112.9-13.7 42.4 0 80.3 4.9 113.5 13.9 11.3-8.6 67.3-48.8 121.4-43.9 2.9 7.7 24.7 58.3 5.5 118.1 32.5 36.8 49 82.8 49 132.4 0 102.3-59 188.3-200.2 213.2 23.5 23.3 38.1 55.5 38.1 91.1v112.7c0.8 9 0 17.9 15.1 17.9C832.7 877 960.4 709.4 960.4 512.1c0-247.5-200.6-447.9-447.9-447.9C265 64.1 64.6 264.5 64.6 512z"></path>
  </svg>
</a><a href="https://www.google.cn/" target="_blank" rel="noopener noreferrer">
  <svg class="icon icon-google+" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <path d="M933.714286 432.457143H520.8v169.714286h235.885714c-10.171429 54.857143-41.028571 101.257143-87.542857 132.342857-39.314286 26.285714-89.485714 41.828571-148.457143 41.828571-114.171429 0-210.742857-77.142857-245.257143-180.8-8.685714-26.285714-13.714286-54.4-13.714285-83.314286s5.028571-57.028571 13.714285-83.314285c34.628571-103.542857 131.2-180.685714 245.371429-180.685715 64.342857 0 122.057143 22.171429 167.542857 65.6l125.714286-125.828571c-76-70.857143-175.085714-114.285714-293.257143-114.285714-171.314286 0-319.542857 98.285714-391.657143 241.6-29.714286 59.2-46.628571 126.171429-46.628571 197.028571S99.428571 650.057143 129.142857 709.257143C201.257143 852.571429 349.485714 950.857143 520.8 950.857143c118.4 0 217.6-39.314286 290.057143-106.285714 82.857143-76.342857 130.742857-188.8 130.742857-322.4 0-31.085714-2.742857-60.914286-7.885714-89.714286z"></path>
  </svg>
</a>
<a href="https://www.youtube.com/" target="_blank" rel="noopener noreferrer">
  <svg class="icon icon-youtube" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <path d="M981.333333 414.293333a362.666667 362.666667 0 0 0-38.826666-176.213333 124.586667 124.586667 0 0 0-73.386667-42.666667A3343.36 3343.36 0 0 0 512 182.186667a3347.2 3347.2 0 0 0-355.84 12.8 122.453333 122.453333 0 0 0-62.293333 31.573333c-38.4 35.413333-42.666667 96-46.933334 147.2a2060.373333 2060.373333 0 0 0 0 276.48 407.466667 407.466667 0 0 0 12.8 85.333333 133.973333 133.973333 0 0 0 30.293334 58.026667 122.026667 122.026667 0 0 0 63.573333 33.28 1927.68 1927.68 0 0 0 277.333333 14.08c149.333333 2.133333 280.32 0 435.2-11.946667a122.88 122.88 0 0 0 65.28-33.28 106.24 106.24 0 0 0 26.026667-42.666666 451.413333 451.413333 0 0 0 22.186667-145.066667c1.706667-23.893333 1.706667-168.106667 1.706666-193.706667zM415.573333 633.6V369.493333l252.586667 132.693334c-70.826667 39.253333-164.266667 83.626667-252.586667 131.413333z"></path>
  </svg>
</a>
<a href="https://music.163.com/#/user/home?id=342119619" target="_blank" rel="noopener noreferrer">
  <svg class="icon icon-cloudmusic" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <path d="M952.17867 503.263237a341.054956 341.054956 0 0 0-56.853199-113.706399 408.604266 408.604266 0 0 0-109.723463-98.352823 304.662484 304.662484 0 0 0-143.257215-42.077792L621.305897 170.238394a40.343287 40.343287 0 0 1 10.792472-36.392472 56.88532 56.88532 0 0 1 36.392472-18.758344 102.785445 102.785445 0 0 1 56.853199 18.758344c6.263488 3.404768 10.792472 9.090088 17.05596 13.073024a57.335006 57.335006 0 0 0 82.999247-70.632873 66.521455 66.521455 0 0 0-22.74128-27.848432 237.691343 237.691343 0 0 0-89.262735-43.202007A170.559598 170.559598 0 0 0 625.288833 6.42409a167.026349 167.026349 0 0 0-60.836135 37.516688 164.328231 164.328231 0 0 0-40.921456 51.713927 156.908407 156.908407 0 0 0-8.54404 113.706399l13.651192 52.870264a284.298118 284.298118 0 0 0-158.064743 109.209535 256.963614 256.963614 0 0 0-43.202007 156.908407 248.419573 248.419573 0 0 0 13.651192 74.487327 205.281807 205.281807 0 0 0 80.718695 104.616312 185.945295 185.945295 0 0 0 136.447679 25.696361 193.879046 193.879046 0 0 0 156.330238-196.705646L708.802008 503.263237c-11.948808-46.060728-24.443664-91.543287-35.814304-137.025847a182.283563 182.283563 0 0 1 47.763112 18.180176 316.611292 316.611292 0 0 1 47.763111 34.690088A239.907654 239.907654 0 0 1 840.752823 529.987453a284.169636 284.169636 0 0 1 0 158.064743 252.241907 252.241907 0 0 1-21.584943 51.167879 308.741782 308.741782 0 0 1-168.279047 144.542033 387.918695 387.918695 0 0 1-130.184191 23.319448 332.607277 332.607277 0 0 1-155.206022-37.516688A367.233124 367.233124 0 0 1 194.87478 672.666499a373.014806 373.014806 0 0 1-20.460727-180.806022A366.173149 366.173149 0 0 1 406.869762 198.536512a57.399247 57.399247 0 0 0 13.073023-100.055207 76.189711 76.189711 0 0 0-63.662735-3.404768A479.815307 479.815307 0 0 0 68.705646 436.163614a488.905395 488.905395 0 0 0 129.027855 450.84266 454.857716 454.857716 0 0 0 248.997741 131.886574 470.885822 470.885822 0 0 0 138.117942 0A454.889837 454.889837 0 0 0 773.042911 952.949561a427.523212 427.523212 0 0 0 170.559598-209.232622 417.276788 417.276788 0 0 0 22.74128-109.209536 378.089837 378.089837 0 0 0-14.165119-131.244166z m-412.747804 118.845671a72.174655 72.174655 0 0 1-56.8532-10.792471 98.352823 98.352823 0 0 1-37.516687-61.382184 170.68808 170.68808 0 0 1 0-65.943287 133.042911 133.042911 0 0 1 33.533751-63.662735 181.35207 181.35207 0 0 1 80.718695-46.606776l39.219072 148.364367a204.189711 204.189711 0 0 1 5.107152 26.146048 79.594479 79.594479 0 0 1-64.208783 73.844918z"></path>
  </svg>
</a>    </div>
     
    <p>&copy; 2021 <a href="/" target="_blank">体奈</a></p>

    
      <p id="hitokoto"></p>
      <script src="https://v1.hitokoto.cn/?c=a&amp;encode=js&select=%23hitokoto" defer></script>
    

    

    <p>Powered by <a href="https://hexo.io" target="_blank" rel="noopener noreferrer">Hexo</a> Theme - <a href="https://github.com/miiiku/flex-block" target="_blank" rel="noopener noreferrer author">flex-block</a></p>
    
    <!--
    <div class="footer-container__texts">
      <p>ヽ｀、ヽ｀｀、ヽ｀ヽ｀、、ヽ｀ヽ、ヽ｀、ヽ｀｀、ヽ、｀｀、、ヽ｀ヽ、｀｀、、ヽ｀ヽ、｀ヽ、｀ヽ、｀ヽ</p>
      <p>｀、ヽ｀｀、ヽ、｀｀｀、｀、ヽ🌙｀｀、｀ヽ｀ヽ、ヽ｀、ヽ｀ヽ、ヽ｀、ヽ｀ヽ、ヽ｀、ヽ｀｀、｀ヽ、｀</p>
      <p>｀、｀｀、｀、ヽ｀｀、、ヽヽ｀、｀ヽ｀ヽ、ヽ｀、ヽ｀ヽ、ヽ｀、、、ヽヽ、｀｀、、ヽ｀、ヽ｀｀、ヽ｀ヽ｀</p>
      <p>ヽ｀、｀｀、｀、ヽ｀｀、、ヽヽ｀、｀、、ヽヽ、｀Time waits for on one 🍓｀、、ヽ｀、ヽ｀｀、ヽ｀ヽ｀</p>
      <p>｀ヽ｀｀、ヽ｀ヽ｀、、ヽ｀ヽ｀ヽ｀ヽ、ヽ｀、ヽ｀｀、ヽ、｀｀、、ヽ｀ヽ、｀｀、、ヽ｀ヽ、｀ヽ、｀ヽ、｀ヽ</p>
    </div>
    -->
  </div>
</footer>
  </div>

  <div class="back-to-top-fixed">
    <svg class="icon icon-back-to-top" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <path d="M725.333333 426.666667c-12.8 0-21.333333-4.266667-29.866667-12.8l-213.333333-213.333333c-17.066667-17.066667-17.066667-42.666667 0-59.733333s42.666667-17.066667 59.733333 0l213.333333 213.333333c17.066667 17.066667 17.066667 42.666667 0 59.733333C746.666667 422.4 738.133333 426.666667 725.333333 426.666667z"></path>
  <path d="M298.666667 426.666667c-12.8 0-21.333333-4.266667-29.866667-12.8-17.066667-17.066667-17.066667-42.666667 0-59.733333l213.333333-213.333333c17.066667-17.066667 42.666667-17.066667 59.733333 0s17.066667 42.666667 0 59.733333l-213.333333 213.333333C320 422.4 311.466667 426.666667 298.666667 426.666667z"></path>
  <path d="M512 896c-25.6 0-42.666667-17.066667-42.666667-42.666667L469.333333 170.666667c0-25.6 17.066667-42.666667 42.666667-42.666667s42.666667 17.066667 42.666667 42.666667l0 682.666667C554.666667 878.933333 537.6 896 512 896z"></path>
</svg> 
  </div>

  
  


  <!-- aplayer 音频 start -->
  <link rel="stylesheet" href="https://unpkg.com/aplayer@1.10.1/dist/APlayer.min.css">
  <script type="text/javascript" src="https://unpkg.com/aplayer@1.10.1/dist/APlayer.min.js"></script>
  <script type="text/javascript">
    const aplayer = document.querySelectorAll(".aplayer");
    aplayer && initaplayer(aplayer);
    function initaplayer(els) {
      let elsArr = Array.from(els);
      elsArr.forEach(el => {
        let params = {
          container: el,
          audio: { ...el.dataset },
          theme: "#b7daff",
          autoplay: true,
          loop: true,
          mutex: true,
        }
        if (el.dataset.lrc) {
          params['lrcType'] = 3
        }
        new APlayer(params);
      });
    }
  </script>
  <!-- aplayer 音频 end -->
  

<!-- dplayer 视频 start -->
<script type="text/javascript" src="https://unpkg.com/dplayer@1.25.1/dist/DPlayer.min.js"></script>
<script type="text/javascript">
  const dplayer = document.querySelectorAll(".dplayer");
  dplayer && initDPlayer(dplayer);
  function initDPlayer(els) {
    let elsArr = Array.from(els);
    elsArr.forEach(el => {
      let url = el.dataset.url;
      let cover = el.dataset.cover;
      let subtitle = el.dataset.subtitle;

      let options = {
        container: el,
        video: { url: url, pic: cover },
        theme: "#b7daff",
        autoplay: true,
        loop: true,
        mutex: true,
      }

      if (subtitle) {
        options.subtitle = {
          url: el.dataset.subtitle,
        }
      }
      new DPlayer(options);
    });
  }
</script>
<!-- dplayer 视频 end -->


<!-- waterfall 瀑布流 start -->

<script src="/hexo/lib/waterfall.min.js"></script>

<script type="text/javascript">

const waterfalls = document.querySelectorAll(".waterfall-container");

if (waterfalls && waterfalls.length > 0) {
  waterfalls.forEach((waterfall, index) => {
    let cls = "waterfall-container-" + index;
    waterfall.classList.add(cls);
    initWaterfall(cls, waterfall);
  });
}

function initWaterfall(selector, el) {
  const options = {};
  if (Object.keys(el.dataset).length > 0) {
    for (let k in el.dataset) {
      options[k] = el.dataset[k];
    }
  }
  waterfall(`.${selector}`, options);
}
</script>
<!-- waterfall 瀑布流 end -->


  <!-- zoom start -->
  
<script src="/hexo/lib/zoom.min.js"></script>

  <script type="text/javascript">
    document.querySelector(".article-content") && zoom(".article-content");
  </script>
  <!-- zoom end -->
  



  


  


  




<script src="/hexo/js/script.js"></script>


  
  <!-- 尾部用户自定义相关内容 -->
<script src="/hexo/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>